package com.sunny.shop.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunny.shop.exception.httpe.PrameterException;
import com.sunny.shop.model.User;
import com.sunny.shop.repository.UserRepository;
import com.sunny.shop.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxAuthenticationService {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret;
    @Value("${wx.code2session}")
    private String code2sessionUrl;
    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private UserRepository userRepository;

    public String code2Session(String code){
        String url = MessageFormat.format(this.code2sessionUrl,this.appid,this.appsecret, code);
        RestTemplate res = new RestTemplate();
        String message = res.getForObject(url, String.class);
        Map<String, Object> map = new HashMap<>();
        try {
            map = mapper.readValue(message, Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return this.registerUser(map);
    }

    private String registerUser(Map<String, Object> session){
        String openid = (String)session.get("openid");
        if(openid == null){
            throw new PrameterException(20002);
        }
        User user = this.userRepository.findOneByOpenid(openid);
        if(user != null){
            return JwtToken.makeToken(user.getId());
        }
        User userInfo = User.builder().openid(openid).integral(0).build();
        userRepository.save(userInfo);
        return JwtToken.makeToken(userInfo.getId());
    }
}
